package com.gcong.service;

import com.gcong.dao.mapper.StudentMapper;
import com.gcong.model.Student;
import com.gcong.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by 巩聪 on 2018/1/7.
 */
@Service
public class StudentService {
    @Autowired
    StudentRepository studentRepository;

    @Autowired
    StudentMapper studentMapper;

    @Transactional
    public Student addNewStudent(Student student) {
        return studentRepository.save(student);
    }

    @Transactional
    public void deleteStudent(Long id) {
        studentRepository.delete(id);
    }

    @Transactional
    public Student updateStudent(Student student) {
//        Student stu = studentRepository.findOne(student.getId());
        /*tm好复杂*/
//        Field[] fields = student.getClass().getDeclaredFields();
//        for (Field field : fields) {
//            field.setAccessible(true);
//            if (field.get(student) != null) {
//
//            }
//        }
        return studentRepository.save(student);
    }

    public List<Student> findAll() {
        return studentRepository.findAll();
    }

    public List<Student> findByName(String name) {
        return studentRepository.findByName(name);
    }

    public Student findById(Long id) {
        return studentMapper.getOne(id);
    }

    /*验证事务管理*/
    public void saveTwoStudent() {
        Student stu1 = new Student();
        studentRepository.save(stu1);

        //stu2有个属性值不符合数据库要求，比如字符串长度
        //如果没有事务管理，则stu1会插入成功，stu2插入失败
        //如果有事务管理，则都插入失败
        Student stu2 = new Student();
        studentRepository.save(stu2);

    }
}
